package com.cjack.frenchexcel.controller;

import com.alibaba.fastjson.JSONObject;
import com.cjack.frenchexcel.config.AjaxResult;
import com.cjack.frenchexcel.config.CommonConfig;
import com.cjack.frenchexcel.config.LayPage;
import com.cjack.frenchexcel.dao.ConsumerRecordDao;
import com.cjack.frenchexcel.dao.UserAdminDao;
import com.cjack.frenchexcel.enumInfo.InvoiceReimbursementStatusEnum;
import com.cjack.frenchexcel.model.CloudDiskModel;
import com.cjack.frenchexcel.request.HandBindConsumerRequest;
import com.cjack.frenchexcel.service.CloudDiskService;
import com.cjack.frenchexcel.table.AdminUserTable;
import com.cjack.frenchexcel.table.ConsumerRecordTable;
import com.cjack.frenchexcel.util.CustomerStringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.StopWatch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/cloudDisk")
public class CloudDiskEndpoint extends BaseEndpoint {

    @Autowired
    CloudDiskService service;
    @Autowired
    private ConsumerRecordDao consumerRecordDao;
    @Autowired
    private UserAdminDao userAdminDao;
    @Autowired
    ThreadPoolExecutor defaultThreadPoolExecutor;

    /**
     * 获取当前id下一条未编辑的数据
     */
    @RequestMapping(value = "/getNext/unDeal/{id}", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getNextUnDeal(HttpSession session, @PathVariable Long id) {
        Object adminUserId = session.getAttribute(CommonConfig.SESSION_NAME);
        return AjaxResult.SUCCESS(service.getNextUnDeal(adminUserId, id));
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult list(HttpSession session, LayPage layPage, CloudDiskModel model) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Object adminUserId = session.getAttribute(CommonConfig.SESSION_NAME);
        model.setAdminUserId((Long) adminUserId);
        Page<CloudDiskModel> resultPage = service.pageList(layPage, model);
        stopWatch.stop();
        log.info("查询列表耗时 {}s", stopWatch.getTime(TimeUnit.SECONDS));
        stopWatch.reset();
        stopWatch.start();
        for (CloudDiskModel data : resultPage.getContent()) {
            CompletableFuture.runAsync(() -> {
                if (data.getOtherId() != null && data.getOtherId() != 0L) {
                    try {
                        ConsumerRecordTable consumerRecordTable = consumerRecordDao.getOne(data.getOtherId());
                        if (consumerRecordTable != null && "PASS".equals(consumerRecordTable.getInvoiceStatus())) {
                            data.setConsumerReviewStatus("PASS");
                        }
                    } catch (Exception e) {
                        log.error(e.getMessage());
                    }
                }
                if (data.getAdminUserId() != null && data.getAdminUserId() != 0L) {
                    AdminUserTable adminUserTable = userAdminDao.getOne(data.getAdminUserId());
                    data.setNom(adminUserTable.getNom());
                    data.setPrenom(adminUserTable.getPrenom());
                }
            }, defaultThreadPoolExecutor);
        }
        stopWatch.stop();
        log.info("组装数据列表耗时 {}s", stopWatch.getTime(TimeUnit.SECONDS));
        layPage.setData(resultPage.getContent());
        layPage.setCount(Long.valueOf(resultPage.getTotalElements()).intValue());
        return AjaxResult.SUCCESS(layPage);
    }

    /**
     * 导出excel，分两步走，先生成excel放到对应的目录，再返回生成的excel的地址给浏览器端
     */
    @RequestMapping(value = "/exportAsExcel", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult exportAsExcel(HttpSession session, CloudDiskModel model) {
        Object loginUserId = session.getAttribute(CommonConfig.SESSION_NAME);
        model.setAdminUserId((Long) loginUserId);
        JSONObject json = service.exportAsExcel(model);
        return AjaxResult.SUCCESS(json);
    }

    /**
     * 税务导出
     * 导出excel，分两步走，先生成excel放到对应的目录，再返回生成的excel的地址给浏览器端
     */
    @RequestMapping(value = "/invoiceExportAsExcel", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult invoiceExportAsExcel(HttpSession session, CloudDiskModel model) {
        Object loginUserId = session.getAttribute(CommonConfig.SESSION_NAME);
        model.setAdminUserId((Long) loginUserId);
        JSONObject json = service.invoiceExportAsExcel(model);
        return AjaxResult.SUCCESS(json);
    }

    /**
     * 导出excel，分两步走，先生成excel放到对应的目录，再返回生成的excel的地址给浏览器端
     */
    @RequestMapping(value = "/exportInvoice", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult exportInvoice(HttpSession session, CloudDiskModel model) {
        Object loginUserId = session.getAttribute(CommonConfig.SESSION_NAME);
        model.setAdminUserId((Long) loginUserId);
        JSONObject json = service.exportInvoice(model);
        return AjaxResult.SUCCESS(json);
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/addOrUpdate", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult addOrUpdate(CloudDiskModel model, HttpSession session) {
        if (isAdd(model.getId())) {
            model.setCreateTime(new Date());
            model.setContentType(3);//新增默认为发票
        }
        Object adminUserId = session.getAttribute(CommonConfig.SESSION_NAME);
        if (adminUserId == null) {
            return AjaxResult.ERROR();
        }
        if (StringUtils.isEmpty(model.getName())) {
            model.setName(CustomerStringUtil.randomStr(16));
        }
        if (model.getContentType() == 3) {
            model.setInvoiceReimbursementStatus(InvoiceReimbursementStatusEnum.UN_REIMBURSEMENT.getCode());
        }
        model.setUpdateTime(new Date());
        //如果没有选择文件归属人，则默认当前登录人为文件归属人
        if (model.getAdminUserId() == null || model.getAdminUserId() == 0l) {
            model.setAdminUserId((Long) adminUserId);
        }
        return service.save(model);
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult del(@RequestParam("ids") String ids) {
        service.del(ids);
        return AjaxResult.SUCCESS("删除成功");
    }

    /**
     * 解除绑定
     */
    @RequestMapping(value = "/unBindConsumer", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult unBindConsumer(@RequestParam("id") Long id) {
        return service.unBindConsumer(id);
    }

    /**
     * 自动分类，id=-1代表批量操作
     */
    @RequestMapping(value = "/autoSetType", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult autoSetType(CloudDiskModel model) {
        if (model.getId().equals(-1l)) {
            return service.autoSetType();
        } else {
            return service.autoSetType(model);
        }
    }

    /**
     * 自动绑定，id=-1代表批量操作
     */
    @RequestMapping(value = "/bindComsumer", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult bindComsumer(CloudDiskModel model) {
        if (model.getId().equals(-1l)) {
            return service.bindConsumer();
        } else {
            return service.bindConsumer(model);
        }
    }

    /**
     * 自动绑定，id=-1代表批量操作
     */
    @RequestMapping(value = "/handBindConsumer", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult handBindConsumer(HandBindConsumerRequest request) {
        return service.handBindConsumer(request);
    }
}
